use serde::Deserialize;

use crate::models::models::components::v2ray::version::ComponentV2rayVersion;
use crate::runtime::os;
use crate::runtime::response::MagicBoxResponse;
use crate::runtime::result::MagicBoxResult;
use crate::utils::request;

const RELEASES: &'static str = "https://api.github.com/repos/v2fly/v2ray-core/releases?per_page=100";

#[derive(Debug, Default, Clone, Deserialize)]
struct GithubReleaseAsset {
    name: String,
    browser_download_url: String,
}

#[derive(Debug, Default, Clone, Deserialize)]
struct GithubRelease {
    name: String,
    published_at: String,
    assets: Vec<GithubReleaseAsset>,
}

#[tauri::command(rename_all = "snake_case")]
pub(crate) async fn invoke_component_v2ray_versions() -> MagicBoxResult<MagicBoxResponse<Vec<ComponentV2rayVersion>>> {
    let response = request::github_get_data::<Vec<GithubRelease>>(RELEASES).await?;

    let version_name = format!("v2ray-{}-{}.zip", os::SYSTEM.to_lowercase(), match os::ARCH {
        "arm64" => "arm64-v8a",
        "x86_64" => "64",
        _ => "",
    });

    let mut result: Vec<ComponentV2rayVersion> = Vec::new();
    for release in response {
        let version = release.name.replace("v", "");
        let publish_time = release.published_at.replace("T", " ").replace("Z", "");

        let mut name = "";
        let mut download = "";
        for asset in &release.assets {
            if version_name == asset.name {
                name = &asset.name;
                download = &asset.browser_download_url;
            }
        }

        result.push(ComponentV2rayVersion { name: name.to_string(), version, publish_time, download: download.to_string() });
    }

    Ok(MagicBoxResponse::new_success(result))
}